// 初始化任务数组
let tasks = JSON.parse(localStorage.getItem('liushiyu_tasks')) || [];

// 初始化示例任务（如果本地存储为空）
if (tasks.length === 0) {
    tasks = [
        {
            id: 1,
            title: "完成数学作业",
            time: "09:00",
            description: "完成第5章的练习题和复习题",
            completed: false
        },
        {
            id: 2,
            title: "英语阅读",
            time: "14:00",
            description: "阅读《简爱》第3章并做笔记",
            completed: false
        },
        {
            id: 3,
            title: "物理实验报告",
            time: "16:30",
            description: "整理上周实验数据并撰写报告",
            completed: true
        }
    ];
    saveTasks();
}

// DOM元素
const taskForm = document.getElementById('taskForm');
const taskTitle = document.getElementById('taskTitle');
const taskTime = document.getElementById('taskTime');
const taskDescription = document.getElementById('taskDescription');
const tasksContainer = document.getElementById('tasksContainer');
const dateDisplay = document.getElementById('dateDisplay');
const filterButtons = document.querySelectorAll('.filter-btn');
let currentFilter = 'all';

// 设置当前日期
function setCurrentDate() {
    const now = new Date();
    const options = { 
        year: 'numeric', 
        month: 'long', 
        day: 'numeric', 
        weekday: 'long' 
    };
    dateDisplay.textContent = now.toLocaleDateString('zh-CN', options);
}

// 保存任务到本地存储
function saveTasks() {
    localStorage.setItem('liushiyu_tasks', JSON.stringify(tasks));
}

// 生成唯一ID
function generateId() {
    return Date.now().toString(36) + Math.random().toString(36).substr(2);
}

// 添加新任务
function addTask(e) {
    e.preventDefault();
    
    const newTask = {
        id: generateId(),
        title: taskTitle.value.trim(),
        time: taskTime.value,
        description: taskDescription.value.trim(),
        completed: false
    };
    
    tasks.push(newTask);
    saveTasks();
    renderTasks();
    
    // 重置表单
    taskForm.reset();
}

// 切换任务完成状态
function toggleTaskCompletion(taskId) {
    tasks = tasks.map(task => {
        if (task.id === taskId) {
            return { ...task, completed: !task.completed };
        }
        return task;
    });
    
    saveTasks();
    renderTasks();
}

// 删除任务
function deleteTask(taskId) {
    if (confirm('确定要删除这个任务吗？')) {
        tasks = tasks.filter(task => task.id !== taskId);
        saveTasks();
        renderTasks();
    }
}

// 渲染任务列表
function renderTasks() {
    // 过滤任务
    let filteredTasks = tasks;
    if (currentFilter === 'pending') {
        filteredTasks = tasks.filter(task => !task.completed);
    } else if (currentFilter === 'completed') {
        filteredTasks = tasks.filter(task => task.completed);
    }
    
    // 按时间排序
    filteredTasks.sort((a, b) => {
        if (a.time < b.time) return -1;
        if (a.time > b.time) return 1;
        return 0;
    });
    
    // 清空容器
    tasksContainer.innerHTML = '';
    
    // 显示空状态
    if (filteredTasks.length === 0) {
        const emptyState = document.createElement('div');
        emptyState.className = 'empty-state';
        emptyState.innerHTML = `
            <p>📝</p>
            <p>${currentFilter === 'all' ? '还没有任何任务' : 
                currentFilter === 'pending' ? '没有待完成的任务' : '没有已完成的任务'}</p>
        `;
        tasksContainer.appendChild(emptyState);
        return;
    }
    
    // 渲染任务卡片
    filteredTasks.forEach(task => {
        const taskCard = document.createElement('div');
        taskCard.className = `task-card ${task.completed ? 'completed' : ''}`;
        taskCard.innerHTML = `
            <h3>${task.title}</h3>
            <span class="task-time">${task.time}</span>
            <p class="task-description">${task.description || '暂无详细描述'}</p>
            <div class="task-actions">
                <button class="complete-btn" onclick="toggleTaskCompletion('${task.id}')">
                    ${task.completed ? '已完成' : '标记完成'}
                </button>
                <button class="delete-btn" onclick="deleteTask('${task.id}')">删除</button>
            </div>
        `;
        tasksContainer.appendChild(taskCard);
    });
}

// 初始化过滤器按钮
function initFilterButtons() {
    filterButtons.forEach(button => {
        button.addEventListener('click', () => {
            // 移除所有按钮的active类
            filterButtons.forEach(btn => btn.classList.remove('active'));
            // 为当前按钮添加active类
            button.classList.add('active');
            // 更新当前过滤器
            currentFilter = button.dataset.filter;
            // 重新渲染任务
            renderTasks();
        });
    });
}

// 初始化应用
function initApp() {
    setCurrentDate();
    renderTasks();
    initFilterButtons();
    
    // 添加事件监听器
    taskForm.addEventListener('submit', addTask);
    
    // 设置当前时间为默认值
    const now = new Date();
    const hours = now.getHours().toString().padStart(2, '0');
    const minutes = now.getMinutes().toString().padStart(2, '0');
    taskTime.value = `${hours}:${minutes}`;
}

// 当文档加载完成后初始化应用
document.addEventListener('DOMContentLoaded', initApp);